//
//  ChallengeViewController.m
//  namefight
//
//  Created by nasa on 11-3-31.
//  Copyright 2011年 nasawz.com. All rights reserved.
//

#import "ChallengeViewController.h"
#import "PersonIndexer.h"

@interface ChallengeViewController (PrivateMethods)
- (void)hideGradientBackground:(UIView*)theView;
-(void)launchMailAppOnDevice:(NSString *)mail;
-(void)displayComposerSheet :(NSString *)mail;
- (NSString *)getStrWithStr:(NSString *)str ByCSS:(NSString *)css;
- (NSString *)getStrWithNum:(int)num ByCSS:(NSString *)css;
@end
@implementation ChallengeViewController

NSTimer *timer;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        p1 = [[[PersonIndexer shareInstance] p1] retain];
        p2 = [[[PersonIndexer shareInstance] p2] retain];
        NSDictionary * p1_propertys = [PersonIndexer createPersonProperty:p1];
        NSDictionary * p2_propertys = [PersonIndexer createPersonProperty:p2];
        
        blood1 = [[p1_propertys objectForKey:@"vit"] intValue];
        blood2 = [[p2_propertys objectForKey:@"vit"] intValue];
        
        oriBlood1 = [[p1_propertys objectForKey:@"vit"] intValue];
        oriBlood2 = [[p2_propertys objectForKey:@"vit"] intValue];
        
        dex1 = [[p1_propertys objectForKey:@"dex"] intValue];
        dex2 = [[p2_propertys objectForKey:@"dex"] intValue];
        
        agi1 = [[p1_propertys objectForKey:@"agi"] intValue];
        agi2 = [[p2_propertys objectForKey:@"agi"] intValue];
        
        act1 = [[p1_propertys objectForKey:@"act"] intValue];
        act2 = [[p2_propertys objectForKey:@"act"] intValue];
        
        self.title = [NSString stringWithFormat:@"%@ vs %@",p1,p2];
        self.hidesBottomBarWhenPushed = YES;
        
    }
    return self;
}

- (void)dealloc
{
    NSLog(@"ChallengeViewController dealloc");
  
    TT_RELEASE_SAFELY(_actionSheet);
    TT_RELEASE_SAFELY(_shareDialog);
    TT_RELEASE_SAFELY(p1);
    TT_RELEASE_SAFELY(p2);
    TT_RELEASE_SAFELY(acts);
    TT_RELEASE_SAFELY(hitPoints);
    
    
    _webView.delegate = nil;
    TT_RELEASE_SAFELY(_webView);
    TT_RELEASE_SAFELY(_toolbar);
    TT_RELEASE_SAFELY(_actionButton);
    TT_RELEASE_SAFELY(_reFightButton);
    TT_RELEASE_SAFELY(_pbarBlood1);
    TT_RELEASE_SAFELY(_pbarBlood2);
    
    TT_RELEASE_SAFELY(paper_buttom);
    
    adView.delegate = nil;
    TT_RELEASE_SAFELY(adView);
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)loadView
{
    [super loadView];
    
    CGRect frame = [UIScreen mainScreen].applicationFrame;
    CGRect rect = CGRectMake(0, 36, frame.size.width, frame.size.height - TTToolbarHeight()-36);

    UIImageView * bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"paper_bg.png"]];
    [self.view addSubview:bgView];
    TT_RELEASE_SAFELY(bgView);
    
    
    _webView = [[UIWebView alloc] initWithFrame:rect];
    
    
    
    _webView.delegate = self;
    _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth
    | UIViewAutoresizingFlexibleHeight;
    _webView.scalesPageToFit = YES;
    [self.view addSubview:_webView];
    paper_buttom = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"paper_buttom.png"]];
    paper_buttom.frame =CGRectMake(0, 364, 318, 8);
    [self.view addSubview:paper_buttom];
    
    //toolbar
    UIBarItem* space = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:
                         UIBarButtonSystemItemFlexibleSpace target:nil action:nil] autorelease];
    _actionButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:
                     UIBarButtonSystemItemAction target:self action:@selector(shareAction)];
    
    _reFightButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_fight.png"] style:UIBarButtonItemStylePlain target:self action:@selector(reFight)];
    
    _toolbar = [[UIToolbar alloc] initWithFrame:
                CGRectMake(0, self.view.height - TTToolbarHeight(),
                           self.view.width, TTToolbarHeight())];
    _toolbar.autoresizingMask =
    UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    _toolbar.items = [NSArray arrayWithObjects:
                      _reFightButton,
                      space,
                      _actionButton,
                      nil];
    [self.view addSubview:_toolbar];
    
    _reFightButton.enabled = NO;
    _actionButton.enabled = NO;
    
    NSString * path = [[NSBundle mainBundle] pathForResource:@"content" ofType:@"html"];
    NSData *htmlData = [NSData dataWithContentsOfFile:path];
    [_webView setBackgroundColor:[UIColor clearColor]];
    [self hideGradientBackground:_webView];
    
    NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
	NSURL *baseURL = [[NSURL alloc] initFileURLWithPath:resourcePath isDirectory:YES];
    
    
    
    [_webView 	loadData:htmlData 
				   MIMEType:@"text/html"	
		   textEncodingName:@"UTF-8" 
					baseURL:baseURL];
    
    acts = [[NSArray alloc] initWithObjects:
            @"%@一巴掌打在%@的脸上",
            @"%@用语言侮辱，骂的%@狗血淋头",
            @"%@大声的嘲笑%@",
            @"%@一记右钩拳打的%@眼冒金星",
            @"%@飞起一风神腿踢向%@",
            @"%@张开血盆大口，用力的咬，咬的%@全身都是大牙印",
            @"%@使劲捏%@的脑袋",
            @"%@拿起一块板砖砸向%@",
            @"%@抓起一把铁锨猛的抡向%@,差点挂掉",
            @"%@狠狠的用眼睛瞪%@",
            @"%@使出了绝招：《乳来神掌》，吓的%@撒腿就跑",
            @"%@趁对方没注意,用一个预先准备好的空啤酒瓶给了%@一个爆头",
            @"%@转过身闷骚的放了一个屁，熏的%@差点闭过气",
            @"%@从背后抱住%@一个背摔",
            @"%@正准备正面攻击结果脚下一滑，自己摔了个狗吃屎", nil];
    hitPoints = [[NSArray alloc] initWithObjects:
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5],@"base",[NSNumber numberWithInt:5],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5],@"base",[NSNumber numberWithInt:5],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2],@"base",[NSNumber numberWithInt:2],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:9],@"base",[NSNumber numberWithInt:9],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:10],@"base",[NSNumber numberWithInt:10],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:12],@"base",[NSNumber numberWithInt:12],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:8],@"base",[NSNumber numberWithInt:8],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:16],@"base",[NSNumber numberWithInt:16],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:20],@"base",[NSNumber numberWithInt:20],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:0],@"base",[NSNumber numberWithInt:1],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:7],@"base",[NSNumber numberWithInt:7],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:17],@"base",[NSNumber numberWithInt:17],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:11],@"base",[NSNumber numberWithInt:11],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:7],@"base",[NSNumber numberWithInt:7],@"rand", nil],
                 [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1],@"base",[NSNumber numberWithInt:1],@"rand", nil],nil];
    
    
    _bloodBar = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bar_blood.png"]];
    [self.view addSubview:_bloodBar];
    
    _pbarBlood1 = [[UIProgressBar alloc] initWithFrame:CGRectMake(8, 8, 148, 20)];
    _pbarBlood1.minValue = 0;
    _pbarBlood1.maxValue = oriBlood1;
    _pbarBlood1.currentValue = blood1;	
    [_pbarBlood1 setLineColor:[UIColor blackColor]];	
    [_pbarBlood1 setProgressColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"blood.png"]]];	
    [_pbarBlood1 setProgressRemainingColor:[UIColor blackColor]];
    [_bloodBar addSubview:_pbarBlood1];	    
    
    
    _pbarBlood2 = [[UIProgressBar alloc] initWithFrame:CGRectMake(164, 8, 148, 20)];
    _pbarBlood2.minValue = 0;
    _pbarBlood2.maxValue = oriBlood2;
    _pbarBlood2.currentValue = blood2;	
    [_pbarBlood2 setLineColor:[UIColor blackColor]];	
    [_pbarBlood2 setProgressColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"blood.png"]]];	
    [_pbarBlood2 setProgressRemainingColor:[UIColor blackColor]];
    [_bloodBar addSubview:_pbarBlood2];	  
    
    
    // Place an ad at the top of the screen of an iPhone/iPod Touch.
    CGRect adFrame = CGRectZero;
    adFrame.size = GAD_SIZE_320x50;
    
    // Create and setup the ad view.
    adView = [[GADBannerView alloc] initWithFrame:adFrame];
    adView.rootViewController = self;
    adView.adUnitID = @"a14dafd0c1b611c";
    
    // Place the ad view onto the screen.
    //   [self.view addSubview:adView];
    //   [adView release];
    
    // Request an ad without any additional targeting information.
    
    GADRequest * request = [[GADRequest alloc] init];
//    request.testing = YES;
    [request setLocationWithDescription:@"China"];
    [request addKeyword:@"fight"];
    [request addKeyword:@"avatar"];
    [request addKeyword:@"name"];
    adView.rootViewController = self;
    adView.delegate = self;
    [adView loadRequest:request];
    
}

- (void) onTimer:(NSTimer*)theTimer {
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    

    
    //出手机率
    BOOL isP1;
    if (agi1 > agi2) {
        isP1 = YES;
        //p2有2/5机率出手
        if (rand()%5>2) {
            isP1 = NO;
        }
    }else{
        isP1 = NO;
        //p1有2/5机率出手
        if (rand()%5>2) {
            isP1 = YES;
        }
    }
    
    
    int totalActNum = [acts count];
    int x = rand()%totalActNum;
    //暴击 1/10机率
    BOOL isBj = (rand()%10 == 0)?YES:NO;
    
    NSString * printStr;
    
    if (isP1) {
        //闪避
        BOOL isSan = NO;
        if (dex1>dex2) {
            //p2有1/5机率闪避率
            if (rand()%5==0) {
                isSan = YES;
            }
        }else{
            //p2有1/2机率闪避率
            if (rand()%2 == 0) {
                isSan = YES;
            }
        }     
//        x = x - 1;
        if (x != 14) {
            printStr = [NSString stringWithFormat:[acts objectAtIndex:x],[self getStrWithStr:p1 ByCSS:@"blue"],[self getStrWithStr:p2 ByCSS:@"blue"]];
            int hitPoint = [[[hitPoints objectAtIndex:x] objectForKey:@"base"] intValue] + rand()%[[[hitPoints objectAtIndex:x] objectForKey:@"rand"] intValue];
            if (isBj) {
                hitPoint = hitPoint * 2;
            }
            printStr = [NSString stringWithFormat:@"%@ 造成%@点伤害 %@",printStr,[self getStrWithNum:hitPoint ByCSS:@"red"],(isBj)?[self getStrWithStr:@"[暴击]" ByCSS:@"red"]:@""];
            blood2 = blood2 - hitPoint;
        }else{
            NSLog(@"x = %d",x);
            printStr = [NSString stringWithFormat:[acts objectAtIndex:x],[self getStrWithStr:p1 ByCSS:@"blue"]];
            int hitPoint = [[[hitPoints objectAtIndex:x] objectForKey:@"base"] intValue] + rand()%[[[hitPoints objectAtIndex:x] objectForKey:@"rand"] intValue];
            printStr = [NSString stringWithFormat:@"%@ 造成%@点伤害",printStr,[self getStrWithNum:hitPoint ByCSS:@"red"]];
            blood1 = blood1 - hitPoint;
        }
        
    }else{
        //闪避
        BOOL isSan = NO;
        if (dex2>dex1) {
            //p1有1/5机率闪避率
            if (rand()%5==0) {
                isSan = YES;
            }
        }else{
            //p1有1/2机率闪避率
            if (rand()%2 == 0) {
                isSan = YES;
            }
        }     
        
        if (x!=14) {
            printStr = [NSString stringWithFormat:[acts objectAtIndex:x],[self getStrWithStr:p2 ByCSS:@"blue"],[self getStrWithStr:p1 ByCSS:@"blue"]];
            int hitPoint = [[[hitPoints objectAtIndex:x] objectForKey:@"base"] intValue] + rand()%[[[hitPoints objectAtIndex:x] objectForKey:@"rand"] intValue];
            if (isBj) {
                hitPoint = hitPoint * 2;
            }
            printStr = [NSString stringWithFormat:@"%@ 造成%@点伤害 %@",printStr,[self getStrWithNum:hitPoint ByCSS:@"red"],(isBj)?[self getStrWithStr:@"[暴击]" ByCSS:@"red"]:@""];
            blood1 = blood1 - hitPoint;
        }else{
            NSLog(@"x = %d",x);
            printStr = [NSString stringWithFormat:[acts objectAtIndex:x],[self getStrWithStr:p2 ByCSS:@"blue"]];
            int hitPoint = [[[hitPoints objectAtIndex:x] objectForKey:@"base"] intValue] + rand()%[[[hitPoints objectAtIndex:x] objectForKey:@"rand"] intValue];
            printStr = [NSString stringWithFormat:@"%@ 造成%@点伤害",printStr,[self getStrWithNum:hitPoint ByCSS:@"red"]];
            blood2 = blood2 - hitPoint;
        }
    }
    
    _pbarBlood1.currentValue = blood1;
    _pbarBlood2.currentValue = blood2;
    
    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"addstring('%@','');",printStr]];
//    NSLog(@"======ontimer");
    BOOL isEnd = NO;
    if (blood2<0) {
        NSString * p1winStr;
        int killPoint = oriBlood2 - blood2;
        if (blood1>=50) {
            p1winStr = [NSString stringWithFormat:@"恭喜%@获得辉煌的胜利,残忍的用%@点恐怖的伤害迅速的秒杀掉了%@",[self getStrWithStr:p1 ByCSS:@"blue"],[self getStrWithNum:killPoint ByCSS:@"red"],[self getStrWithStr:p2 ByCSS:@"blue"]];
        }else{
            p1winStr = [NSString stringWithFormat:@"恭喜%@获胜利,共对%@造成%@点伤害",[self getStrWithStr:p1 ByCSS:@"blue"],[self getStrWithStr:p2 ByCSS:@"blue"],[self getStrWithNum:killPoint ByCSS:@"red"]];
        }
        TT_INVALIDATE_TIMER(timer);
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"addstring('%@','result_block');",p1winStr]];
        isEnd = YES;
        //TTAlertNoTitle(p1winStr);
    }
    if (blood1<0) {
        NSString * p2winStr;
        int killPoint = oriBlood1 - blood1;
        if (blood1>=50) {
            p2winStr = [NSString stringWithFormat:@"恭喜%@获得辉煌的胜利,残忍的用%@点恐怖的伤害迅速的秒杀掉了%@",[self getStrWithStr:p2 ByCSS:@"blue"],[self getStrWithNum:killPoint ByCSS:@"red"],[self getStrWithStr:p1 ByCSS:@"blue"]];
        }else{
            p2winStr = [NSString stringWithFormat:@"恭喜%@获胜利,共对%@造成%@点伤害",[self getStrWithStr:p2 ByCSS:@"blue"],[self getStrWithStr:p1 ByCSS:@"blue"],[self getStrWithNum:killPoint ByCSS:@"red"]];
        }
        TT_INVALIDATE_TIMER(timer);
        [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"addstring('%@','result_block');",p2winStr]];
        isEnd = YES;
        //TTAlertNoTitle(p2winStr);
    }
    
    if (isEnd) {
        _reFightButton.enabled = YES;
        _actionButton.enabled = YES;
    }else{
        _reFightButton.enabled = NO;
        _actionButton.enabled = NO;
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}

- (NSString *)getStrWithStr:(NSString *)str ByCSS:(NSString *)css {
    NSString * pf_css = @"<span class=\"%@\">%@</span>";
    return [NSString stringWithFormat:pf_css,css,str];
}

- (NSString *)getStrWithNum:(int)num ByCSS:(NSString *)css {
    return [self getStrWithStr:[NSString stringWithFormat:@"%d",num] ByCSS:css];
}

- (void) hideGradientBackground:(UIView*)theView
{
    for (UIView * subview in theView.subviews)
    {
        if ([subview isKindOfClass:[UIImageView class]])
            subview.hidden = YES;
        
        [self hideGradientBackground:subview];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}


- (void)viewDidUnload
{
    NSLog(@"ChallengeViewController viewDidUnload");
    [super viewDidUnload];
}
- (void)viewWillDisappear:(BOOL)animated {
    TT_INVALIDATE_TIMER(timer);
    [super viewWillDisappear:animated];
}
#pragma -
- (void)reFight {
    _reFightButton.enabled = NO;
    _actionButton.enabled = NO;
    
    blood1 = oriBlood1;
    blood2 = oriBlood2;
    
    [_webView stringByEvaluatingJavaScriptFromString:@"clearResult();"];
    
    TT_INVALIDATE_TIMER(timer);
    timer = [NSTimer scheduledTimerWithTimeInterval: 0.8
                                             target: self
                                           selector:@selector(onTimer:)
                                           userInfo: nil repeats:YES];
}
#pragma -
#pragma share friends
- (void)shareAction {
//    NSLog(@"shareAction ＝ %@",_actionSheet);
    if (nil == _actionSheet) {
        _actionSheet = [[UIActionSheet alloc] initWithTitle:@"分享好友"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                     destructiveButtonTitle:nil
                                          otherButtonTitles:@"QQ空间",@"分享到Sina微博",@"分享到人人网",@"分享到开心网",@"发送邮件",
                        nil];
        [_actionSheet showInView: self.view];
    } else {
        [_actionSheet showInView: self.view];
    }
}
- (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
//    NSLog(@"buttonIndex = %d",buttonIndex);
    
    NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   @"http://itunes.apple.com/us/app/id429842317?mt=8#", @"url",
                                   @"姓名大乱斗－和好友一决胜负吧～", @"title",
                                   @"1502474",@"uid",
                                   nil]; 
    
    if (buttonIndex == 0) {
        [params setObject:@"qzone" forKey:@"webid"];
    }
    if (buttonIndex == 1) {
        [params setObject:@"tsina" forKey:@"webid"];
    }
    if (buttonIndex == 2) {
        [params setObject:@"renren" forKey:@"webid"];
    }
    if (buttonIndex == 3) {
        [params setObject:@"kaixin001" forKey:@"webid"];
    }
    if (buttonIndex == 4) {
		NSString* mail = nil;
		
		Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
		if (mailClass != nil)
		{
			if ([mailClass canSendMail])
			{
				[self displayComposerSheet:mail];
			}
			else
			{
				[self launchMailAppOnDevice:mail];
			}
		}
		else
		{
			[self launchMailAppOnDevice:mail];
		}        
    }
    
    if (buttonIndex != 4 && buttonIndex != 5) {
        [_shareDialog release];
        _shareDialog = [[ShareDialog alloc] initWithURL:@"http://www.jiathis.com/send/" Params:params];
        [_shareDialog show];
    }
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request
 navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView*)webView {
}
- (void)webViewDidFinishLoad:(UIWebView*)webView {
    //self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    TT_INVALIDATE_TIMER(timer);
    timer = [NSTimer scheduledTimerWithTimeInterval: 0.8
                                             target: self
                                           selector:@selector(onTimer:)
                                           userInfo: nil repeats:YES];
    
}
- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error {
}
#pragma -
#pragma send email
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{	
    //message.hidden = NO;
    // Notifies users about errors associated with the interface
    
	[self dismissModalViewControllerAnimated:YES];
}
-(void)launchMailAppOnDevice:(NSString *)mail
{
    //NSString *recipients = @"mailto:first@example.com?cc=second@example.com,third@example.com&subject=Hello from California!";
	NSString *recipients = [NSString stringWithFormat:@"mailto:%@",mail];
    
    NSString * bodyHtml = [_webView stringByEvaluatingJavaScriptFromString:@"getResult();"];
    NSString * appLink = [NSString stringWithFormat:@"<p><a href=\"%@\">来自姓名大乱斗</p>",@"http://itunes.apple.com/us/app/id429842317?mt=8#"];  
	NSString * emailBody = [NSString stringWithFormat:@"&body=%@%@",bodyHtml,appLink];
    
	NSString *body = emailBody;
	
	NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
-(void)displayComposerSheet :(NSString *)mail
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
    //[picker setSubject:@"Hello from California!"];
	
	
    // Set up recipients
//	NSArray *toRecipients = [NSArray arrayWithObject:mail]; 
    //NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil]; 
    //NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"]; 
	
//	[picker setToRecipients:toRecipients];
    //[picker setCcRecipients:ccRecipients];	
    //[picker setBccRecipients:bccRecipients];
	
    // Attach an image to the email
    //NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"png"];
    //NSData *myData = [NSData dataWithContentsOfFile:path];
    //[picker addAttachmentData:myData mimeType:@"image/png" fileName:@"rainy"];
	
    // Fill out the email body text
    NSString * bodyHtml = [_webView stringByEvaluatingJavaScriptFromString:@"getResult();"];
    NSString * appLink = [NSString stringWithFormat:@"<p><a href=\"%@\">来自姓名大乱斗</p>",@"http://itunes.apple.com/us/app/id429842317?mt=8#"];  
	NSString * emailBody = [NSString stringWithFormat:@"%@%@",bodyHtml,appLink];
	[picker setMessageBody:emailBody isHTML:YES];
    [picker setSubject:@"姓名大乱斗－战报"];
	
	[self presentModalViewController:picker animated:YES];
    [picker release];
}

#pragma mark -
#pragma mark GADBannerViewDelegate
- (void)adViewDidReceiveAd:(GADBannerView *)view {
	NSLog(@"[AdMob]: 广告已经加载.");    
	
	adView.frame = CGRectMake(0, self.view.height,
                              self.view.width,50);
	
//    CGRect frame1 = [UIScreen mainScreen].applicationFrame;
    
	[self.view addSubview:adView];	
    
	[UIView beginAnimations:@"animateAdBannerOn" context:NULL];
	
    _webView.frame = CGRectMake(0, 36, 320, 282);
    paper_buttom.frame = CGRectOffset(paper_buttom.frame, 0, -48);
    _toolbar.frame = CGRectOffset(_toolbar.frame, 0, -49);
	adView.frame = CGRectMake(0, self.view.height - 50,
                              self.view.width,50);
	
	[UIView commitAnimations];    
}
- (void)adView:(GADBannerView *)view
didFailToReceiveAdWithError:(GADRequestError *)error {
	NSLog(@"[AdMob]: 广告加载失败.");
    NSLog(@"%@",error);
}
@end
